import threading
import time

import socketio
import eventlet

condition = threading.Condition()  # acquire() wait() notify()

#sio = socketio.Client(engineio_logger=True)
"""
sio_server = socketio.Server()
app = socketio.WSGIApp(sio_server, static_files={
    '/': {'content_type': 'textml', 'filename': 'index.html'}
})
"""

conn_flag = False
data = None
trans_flag = False

class Client(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        sio = socketio.Client(engineio_logger=True)

        @sio.event
        def connect():
            print('connected to server')
            sio.emit('ping_from_client')

        @sio.event
        def pong_from_server():
            """
            开启线程，启动自己的服务器，并阻塞客户端线程
            连接回执转给服务器，发送给上一个人
            :return:
            """
            global conn_flag
            condition.acquire()
            while not conn_flag:
                print("还未收到服务端连接回执")
                conn_flag = True
                if conn_flag == True:
                    condition.notify()
                    condition.wait()

            condition.release()
            print('收到服务端连接回执。。。')

        @sio.event
        def send_data():
            print('connected to server')
            global data
            sio.emit('data_from_client', data)


        @sio.event
        def receipt_from_server(sid):
            # 收到数据回执，唤醒服务器线程，使得服务器传回执给上一个人
            sio_server.emit("receipt_from_server", room=sid)

        sio.connect('http://localhost:6606')
        sio.wait()

class Server(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        sio_server = socketio.Server()
        app = socketio.WSGIApp(sio_server, static_files={
            '/': {'content_type': 'textml', 'filename': 'index.html'}
        })

        @sio_server.event
        def ping_from_client(sid):
            global conn_flag
            if conn_flag == True:
                sio_server.emit('pong_from_server', room=sid)

        @sio_server.event
        def data_from_client(sid, d):
            # 服务端线程睡眠，唤醒客户端线程，叫客户端发数据
            global data
            data = d
            Client().
            #sio.emit('data_from_client', data)

        eventlet.wsgi.server(eventlet.listen(('', 5000)), app)

if __name__=="__main__":
    client = Client()
    client.start()
    server = Server()
    server.start()

